package com.example.messagedemo.conifg;

import org.apache.rocketmq.acl.common.AclClientRPCHook;
import org.apache.rocketmq.acl.common.SessionCredentials;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ProducerConfig {
    private final ClientConfig clientConfig;

    public ProducerConfig(ClientConfig clientConfig) {
        this.clientConfig = clientConfig;
    }

    @Bean(destroyMethod = "shutdown")
    public DefaultMQProducer producer() {
        // Token作为生产组
        String producerGroup = clientConfig.getToken();
        // AclClientRPCHook为消息收发认证类,将配置的accessKey和secretKey填充
        AclClientRPCHook aclClientRPCHook = new AclClientRPCHook(new SessionCredentials(clientConfig.getAccessKey(), clientConfig.getSecretKey()));
        // 生产者实例
        DefaultMQProducer producer = new DefaultMQProducer(producerGroup, aclClientRPCHook);
        // producer.setVipChannelEnabled(false);
        // producer.setSendMessageWithVIPChannel(false);
        // producer.setUseHeartbeatV2(true);
        // 设置NameServer地址
        producer.setNamesrvAddr(clientConfig.getNameSvrAddr());//设置RocketMq NameServer 地址
        // 设置消息中心地址
        producer.setCentersrvAddr(clientConfig.getCentSvrAddr());//设置消息中心服务地址
        // 设置消息发送失败重试次数
        producer.setRetryTimesWhenSendAsyncFailed(3);
        try {
            producer.start();// 启动消息生产者
        } catch (MQClientException e) {
            e.printStackTrace();
        }
        return producer;
    }
}
